local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local pcall = pcall
local tonumber = tonumber
local pairs = pairs
local io = io
local util = require 'util'

package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)
_VERSION = '0.1'
local path = "/opt/xyitech/static/"


function get_filename(res)
    local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')
    if filename then 
        return filename[2]
    end
end

function go(args)
    local upload = require "upload"
    local chunk_size = 4096
    local json = require 'cjson'
    local form, err = upload:new(chunk_size)
    local file
    while true do
        if not form then return end
        local typ, res, err = form:read()

        if not typ then
             ngx.say("failed to read: ", err)
             return
        end

        if typ == "header" then
            local file_name = get_filename(res[2])
            
            -- ngx.log(ngx.ERR, path .. file_name)
            if file_name then
                file, err = io.open(path .. file_name, "w+")
                if not file then
                    ngx.print(json.encode({
                        err = 0,
                        msg = "上传失败"
                    }))
                    ngx.exit(200)
                    ngx.say("failed to open file ", file_name)
                    ngx.log(ngx.ERR, err)
                    return
                end
            end

         elseif typ == "body" then
            if file then
                file:write(res)
            end

        elseif typ == "part_end" then
            if file then
                file:close()
            end
            file = nil
        elseif typ == "eof" then
            break

        else
            -- do nothing
        end
    end
    ngx.log(ngx.ERR, "finish")
    ngx.print(json.encode({
        err = 0,
        msg = "上传完成"
    }))
    ngx.exit(200)
end

function base64(image, filename)
    if image then
        local image = ngx.decode_base64(image)
        local file, err = io.open(path .. filename, "w+")
        file:write(image)
        file:close()
    end
end

function base64Controller(args)
    base64(args.image, args.filename)
    ngx.print(json.encode({
        err = 0,
        msg = "上传完成"
    }))
    ngx.exit(200)
end
function default(args)
    local conf = require "conf"
    local user = conf.parse_token(args)
    -- conf.check_permissions(uid, "spoint")
    if args.action == 'go' then
        go(args)
    elseif args.action == 'base64' then
        base64Controller(args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
